// src/renderer/workbench/data-view.js
// electronAPI 通过 preload 注入，无需 require('electron')
// const { formatDate } = require('../../common/utils'); // Removed, use window.Utils.formatDate

// 全局状态存储，用于数据查看功能
const viewStateStore = {}; // { tabId: { allData, dataType, currentPage, pageSize, ... } }

function initializeDataViewModule() {
    // 暴露给 HTML 的全局函数
    window.showDataViewTab = showDataViewTab;
    window.loadDataToView = loadDataToView;
    window.changeDataViewPage = changeDataViewPage;
    window.gotoDataViewPage = gotoDataViewPage;
    window.performDataSearch = performDataSearch;
    window.exportCurrentData = exportCurrentData;
    window.changeDataViewPageSize = changeDataViewPageSize;
    window.toggleSelectAll = toggleSelectAll;
    window.handleDeleteData = handleDeleteData;
    window.handleClearData = handleClearData;
    window.openTemplateManager = openTemplateManager;
    window.loadDataToViewWithSelection = loadDataToViewWithSelection;

    console.log('Data View Module Initialized');
}

let currentDataType = 'bank';

function showDataViewTab() {
    document.querySelectorAll('.dropdown.open').forEach(d => d.classList.remove('open'));

    const content = `
    <div class="data-view-container" style="display:flex; flex-direction:row; height:100%; width:100%; min-height:600px; overflow:hidden; background-color:#f5f7fa;">
      <!-- 左侧侧边栏 -->
      <div class="data-sidebar" style="height:100%;">
        ${window.SidebarModule.createSidebarHtml(currentDataType, 'loadDataToViewWithSelection', '数据分类', null, 'light')}
      </div>

      <!-- 右侧主内容区 -->
      <main class="data-main-content" style="flex:1; display:flex; flex-direction:column; background-color:#fff; padding:10px; overflow:hidden;">
        <!-- 顶部工具栏 -->
        <div class="data-toolbar" style="padding-bottom:10px; border-bottom:1px solid #ebeef5; display:flex; align-items:center; flex-wrap:wrap; gap:5px;">
          <input type="text" id="data-search-keyword" placeholder="请输入关键字，多个关键字以空格隔开" style="width:250px; margin-right:10px; padding:5px 10px; border:1px solid #ddd; border-radius:4px;" onkeydown="if(event.key==='Enter') performDataSearch()">
          <button class="btn-primary" onclick="performDataSearch()" style="display:flex; align-items:center; gap:5px;">
            <span>🔍</span>搜索
          </button>
          <button class="btn-secondary" style="display:flex; align-items:center; gap:5px;">
            <span>⚙️</span>高级查询
          </button>
          <button class="btn-warning" onclick="handleClearData()" style="display:flex; align-items:center; gap:5px; background:#f56c6c; color:white; border-color:#f56c6c;">
            <span>🗑️</span>清空数据
          </button>
          <button class="btn-secondary" onclick="handleDeleteData()" style="display:flex; align-items:center; gap:5px;">
            <span>❌</span>删除选中
          </button>
          <button class="btn-secondary" onclick="openTemplateManager()" style="display:flex; align-items:center; gap:5px;">
            <span>📋</span>模版管理
          </button>
          <button class="btn-secondary" style="display:flex; align-items:center; gap:5px;">
            <span>⭐</span>收藏
          </button>
          <button class="btn-success" onclick="exportCurrentData()" style="display:flex; align-items:center; gap:5px;">
            <span>📥</span>导出数据
          </button>
          <select id="display-options" style="margin-left:10px; padding:5px 10px; border:1px solid #ddd; border-radius:4px;">
            <option>显示选择</option>
            <option>显示全部</option>
          </select>
        </div>

        <!-- 表格区域 -->
        <div id="data-table-container" class="data-table-wrapper" style="height:calc(100vh - 260px); margin-top:10px; overflow:auto; border:1px solid #ebeef5; position:relative; flex-shrink:0;">
          <div id="data-view-container" style="width:100%; height:100%;">
            <p style="text-align:center; color:#999; margin-top:100px; padding:20px;">请点击左侧菜单选择要查看的数据类型</p>
          </div>
        </div>

        <!-- 底部页脚 -->
        <div class="data-footer" style="min-height:60px; max-height:60px; display:flex; align-items:center; justify-content:flex-end; background-color:#ffffff; border:1px solid #ebeef5; border-top:1px solid #dcdfe6; padding:0 20px; margin-top:10px; flex-shrink:0;">
          <div id="pagination-controls">
            <!-- 分页控件将在这里动态生成 -->
          </div>
        </div>
      </main>
    </div>
  `;
    window.createTabInWorkbench('data-view-center', '数据仓库', content);
}

async function loadDataToView(dataType) {
    const container = document.getElementById('data-view-container');
    container.innerHTML = '<p style="text-align:center; color:#666;">加载中...</p>';

    try {
        let caseId = sessionStorage.getItem('currentCaseId');

        // 检查参数是否有效
        if (!caseId) {
            // 如果没有案件ID，调用全局的案件选择功能
            if (window.selectCase) {
                caseId = await window.selectCase();
                if (!caseId) {
                    // 用户取消选择，不继续执行
                    container.innerHTML = '<p style="text-align:center; color:#666;">操作已取消</p>';
                    return;
                }
            } else {
                throw new Error('未找到案件ID，请先在首页选择一个案件');
            }
        }

        if (!dataType) {
            throw new Error('数据类型未指定');
        }

        // 使用 electronAPI 获取数据
        const data = await window.electronAPI.data.get({ caseId, dataType });

        if (!data || data.length === 0) {
            container.innerHTML = '<p style="text-align:center; color:#999;">暂无数据</p>';
            return;
        }

        // 字段字典 (中文表头) - 支持所有8种数据类型
        const fieldDict = {
            // 通用字段
            'id': 'ID', 'case_id': '案件ID', 'created_time': '创建时间',

            // 银行流水
            'transaction_time': '交易时间', 'account_number': '账号', 'transaction_amount': '金额',
            'counterparty_name': '对方户名', 'counterparty_account': '对方账号', 'balance_after': '余额',
            'debit_credit_flag': '借贷标志', 'remarks': '备注',
            'customer_name': '客户名称', 'account_card': '卡号',
            'phone_number': '手机号码', 'account_name': '户名', 'bank_name': '开户行',
            'counterparty_id_number': '对方证件号码', 'counterparty_bank_code': '对方行号',
            'counterparty_bank_name': '对方行名', 'transaction_branch_name': '交易网点名称',
            'teller_number': '柜员号', 'counterparty_card': '对方卡号',
            'transaction_type': '交易类型',

            // 通话记录
            'user_name': '机主姓名', 'user_id': '用户标识', 'user_number': '本机号码',
            'imsi': '国际移动用户识别码', 'opp_user_number': '对方号码', 'a_number': '主叫号码',
            'start_time': '通话开始时间', 'duration': '通话时长', 'call_type': '呼叫类型',
            'lac_id': '位置区编码', 'cell_id': '小区标识', 'esn': '电子序列号',
            'hplmn2': '归属公共陆地移动网络', 'vplmn2': '拜访公共陆地移动网络',
            'opp_roam_areacode': '对方漫游地区号', 'opp_home_areacode': '对方归属地区号',

            // 住宿登记
            'guest_name': '姓名', 'id_number': '身份证号', 'certificate_number': '证件号码',
            'check_in_time': '入住时间', 'check_out_time': '离店时间', 'hotel_name': '旅店名称',
            'room_number': '房间号码', 'hotel_district': '旅店区划', 'hotel_address': '旅店地址',
            'certificate_type': '证件类型', 'nationality': '国籍/地区', 'gender': '性别',
            'ethnicity': '民族', 'birth_date': '出生日期', 'household_district': '户籍地区划',
            'household_address': '户籍地详址',

            // 不动产登记
            'feedback_unit': '反馈单位', 'approval_form': '审批表', 'owner_name': '名称',
            'property_unit_number': '不动产单元号', 'property_address': '房地坐落',
            'building_area': '建筑面积', 'planning_purpose': '规划用途', 'property_nature': '房屋性质',
            'completion_date': '竣工时间', 'land_use_start_date': '土地使用起始时间',
            'land_use_end_date': '土地使用结束时间', 'property_certificate_number': '不动产权证号',
            'registration_authority': '登记机构',

            // 铁路售票
            'passenger_name': '姓名', 'train_number': '车号', 'departure_date': '发车日期',
            'departure_station': '发站', 'arrival_station': '到站', 'carriage_number': '车厢号',
            'seat_number': '座位号', 'ticket_number': '票号', 'ticket_status': '车票状态',

            // 飞机售票
            'passenger_chinese_name': '旅客中文姓名', 'flight_date': '航班日期',
            'departure_port': '起飞港站', 'arrival_port': '到达航站', 'airline_company': '航空公司',
            'flight_number': '航班号', 'departure_time': '离港时间', 'arrival_time': '进港时间',

            // 工商企业
            'name': '名称', 'entity_code': '主体身份代码', 'unified_social_credit_code': '统一社会信用代码',
            'enterprise_name': '企业名称', 'legal_representative': '法定代表人',
            'registration_number': '注册号', 'market_entity_type': '市场主体类型',
            'industry_category': '行业门类', 'industry_code': '行业代码',
            'establishment_date': '成立日期', 'business_scope_type': '业务范围类型',
            'business_scope': '经营范围', 'business_period_start': '经营期限自',
            'business_period_end': '经营期限至', 'registration_status': '登记状态',
            'address': '住所', 'registered_capital': '注册资本',
            'registered_capital_currency': '注册资本币种', 'employee_count': '从业人员总数',

            // 出行记录
            'end_time': '结束时间', 'origin': '出发地', 'destination': '目的地',
            'transport_type': '交通工具'
        };

        const tabId = 'data-view-center';
        // 获取所有不重复的字段名，不仅仅是第一行
        const allKeysSet = new Set();
        data.forEach(row => {
            // 解析 extra_data 并合并到 row 中
            if (row.extra_data) {
                try {
                    const extra = JSON.parse(row.extra_data);
                    Object.assign(row, extra);
                } catch (e) {
                    console.error('解析 extra_data 失败', e);
                }
            }

            // 格式化日期字段
            if (row.transaction_time && window && window.Utils && typeof window.Utils.formatDate === 'function') {
                row.transaction_time = window.Utils.formatDate(row.transaction_time);
            }
            if (row.start_time && window && window.Utils && typeof window.Utils.formatDate === 'function') {
                row.start_time = window.Utils.formatDate(row.start_time);
            }

            Object.keys(row).forEach(key => {
                // 忽略 id, case_id 和 extra_data 本身
                if (key !== 'id' && key !== 'case_id' && key !== 'extra_data') {
                    allKeysSet.add(key);
                }
            });
        });

        // 根据数据类型定义字段顺序
        let keys = Array.from(allKeysSet);
        if (dataType === 'bank') {
            const bankFieldOrder = [
                'customer_name', 'id_number', 'account_card', 'phone_number', 'account_name', 'bank_name',
                'debit_credit_flag', 'transaction_amount', 'balance_after', 'transaction_time',
                'counterparty_card', 'counterparty_account', 'counterparty_name', 'counterparty_id_number',
                'counterparty_bank_code', 'counterparty_bank_name', 'remarks', 'transaction_branch_name', 'teller_number'
            ];

            const orderedKeys = [];
            bankFieldOrder.forEach(field => {
                if (keys.includes(field)) orderedKeys.push(field);
            });
            keys.forEach(key => {
                if (!bankFieldOrder.includes(key)) orderedKeys.push(key);
            });
            keys = orderedKeys;
        } else if (dataType === 'call') {
            const callFieldOrder = [
                'user_name', 'user_id', 'user_number', 'imsi', 'opp_user_number', 'a_number',
                'start_time', 'duration', 'call_type', 'lac_id', 'cell_id',
                'esn', 'hplmn2', 'vplmn2', 'opp_roam_areacode', 'opp_home_areacode'
            ];

            const orderedKeys = [];
            callFieldOrder.forEach(field => {
                if (keys.includes(field)) orderedKeys.push(field);
            });
            keys.forEach(key => {
                if (!callFieldOrder.includes(key)) orderedKeys.push(key);
            });
            keys = orderedKeys;
        }

        // 初始化状态
        viewStateStore[tabId] = {
            allData: data,
            dataType: dataType,
            currentPage: 1,
            pageSize: 50,
            total: data.length,
            keys: keys,
            fieldDict: fieldDict
        };

        // 渲染表格
        renderDataViewTable(tabId);

    } catch (e) {
        // 检查是否是"表不存在"的错误
        if (e.message.includes('no such table:')) {
            container.innerHTML = '<p style="text-align:center; color:#999;">暂无数据，请先导入数据</p>';
        } else {
            container.innerHTML = `<p style="text-align:center; color:red;">加载失败: ${e.message}</p>`;
        }
    }
}

function renderDataViewTable(tabId) {
    const state = viewStateStore[tabId];
    if (!state) return;

    const { allData, filteredData, keys, fieldDict, currentPage, pageSize } = state;

    // 使用过滤后的数据（如果有）或者全部数据
    const displayData = filteredData || allData;
    const total = displayData.length;

    // 更新 state 中的 total，以防不一致
    state.total = total;

    const start = (currentPage - 1) * pageSize;
    const pageData = displayData.slice(start, start + pageSize);
    const totalPages = Math.ceil(total / pageSize) || 1;

    let html = `
            <table class="data-display-table" style="width:100%; border-collapse:collapse; font-size:0.9rem; min-width:${120 * (keys.length + 1)}px; border:1px solid #eee;">
                <thead>
                    <tr style="background:#f8f9fa; position:sticky; top:0; z-index:10;">
                        <th style="width:40px; position:sticky; left:0; z-index:20; background:#e9ecef; border:1px solid #ddd; text-align:center;">
                            <input type="checkbox" id="select-all-rows" onchange="toggleSelectAll(this)">
                        </th>
                        <th style="width:60px; position:sticky; left:40px; z-index:20; background:#e9ecef; border:1px solid #ddd; text-align:center;">序号</th>
    `;

    keys.forEach(k => {
        const displayName = fieldDict[k] || k;
        html += `<th style="min-width:120px; max-width:300px; position:sticky; top:0; z-index:10; background:#f1f1f1; border:1px solid #ddd; padding:8px; text-align:left; font-weight:600;">${displayName}</th>`;
    });

    html += '</tr></thead><tbody>';

    pageData.forEach((row, idx) => {
        const realIdx = start + idx;
        html += `<tr>
            <td style="position:sticky; left:0; background:#f9f9f9; z-index:5; border:1px solid #eee; text-align:center;">
                <input type="checkbox" class="row-checkbox" value="${row.id}">
            </td>
            <td style="position:sticky; left:40px; background:#f9f9f9; z-index:5; border:1px solid #eee; text-align:center; font-size:0.9em; color:#666;">${realIdx + 1}</td>`;

        keys.forEach(k => {
            let cellValue = row[k];
            if (cellValue === null || cellValue === undefined) cellValue = '';
            html += `<td style="padding:6px 8px; border:1px solid #eee; max-width:250px; min-width:120px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">${cellValue}</td>`;
        });
        html += '</tr>';
    });

    html += '</tbody></table>';

    // 添加分页控件
    html += `
    <div class="pagination-bar" style="display:flex; align-items:center; justify-content:flex-end; padding:15px 20px; background:#fff; border-top:1px solid #eee; gap:10px;">
      <span style="color:#606266;">共 ${total} 条</span>
      <select onchange="changeDataViewPageSize('${tabId}', this.value)" style="padding:4px 8px; border:1px solid #dcdfe6; border-radius:4px;">
        <option value="50" ${pageSize === 50 ? 'selected' : ''}>50条/页</option>
        <option value="100" ${pageSize === 100 ? 'selected' : ''}>100条/页</option>
        <option value="200" ${pageSize === 200 ? 'selected' : ''}>200条/页</option>
        <option value="500" ${pageSize === 500 ? 'selected' : ''}>500条/页</option>
        <option value="10000" ${pageSize === 10000 ? 'selected' : ''}>全部</option>
      </select>
      <span style="color:#606266;">前往</span>
      <input type="number" id="goto-page" min="1" max="${totalPages}" value="${currentPage}"
        style="width:50px; padding:4px 8px; border:1px solid #dcdfe6; border-radius:4px; text-align:center;"
        onkeydown="if(event.key==='Enter') gotoDataViewPage('${tabId}', this.value)">
      <span style="color:#606266;">页</span>
      <button class="btn-secondary" onclick="changeDataViewPage('${tabId}', -1)"
        ${currentPage <= 1 ? 'disabled style="opacity:0.5; cursor:not-allowed;"' : ''}>上一页</button>
      <span style="color:#606266; min-width:50px; text-align:center;">${currentPage} / ${totalPages}</span>
      <button class="btn-secondary" onclick="changeDataViewPage('${tabId}', 1)"
        ${currentPage >= totalPages ? 'disabled style="opacity:0.5; cursor:not-allowed;"' : ''}>下一页</button>
    </div>
  `;

    document.getElementById('data-view-container').innerHTML = html;
}

function changeDataViewPage(tabId, delta) {
    const state = viewStateStore[tabId];
    if (!state) return;

    const totalPages = Math.ceil(state.total / state.pageSize);
    const newPage = state.currentPage + delta;

    if (newPage >= 1 && newPage <= totalPages) {
        state.currentPage = newPage;
        renderDataViewTable(tabId);
        document.getElementById('data-view-container').scrollTop = 0;
    }
}

function gotoDataViewPage(tabId, pageStr) {
    const state = viewStateStore[tabId];
    if (!state) return;

    const page = parseInt(pageStr);
    const totalPages = Math.ceil(state.total / state.pageSize);

    if (page >= 1 && page <= totalPages) {
        state.currentPage = page;
        renderDataViewTable(tabId);
    }
}

function performDataSearch() {
    const tabId = 'data-view-center';
    const state = viewStateStore[tabId];
    if (!state || !state.allData) {
        alert('请先选择左侧的数据类型加载数据后再进行搜索。');
        return;
    }

    const keywordInput = document.getElementById('data-search-keyword');
    const keyword = keywordInput.value.trim().toLowerCase();

    if (!keyword) {
        state.filteredData = null;
        state.total = state.allData.length;
        state.currentPage = 1;
        renderDataViewTable(tabId);
        return;
    }

    const keywords = keyword.split(/\s+/).filter(k => k.length > 0);

    const filtered = state.allData.filter(row => {
        const rowStr = Object.values(row).join(' ').toLowerCase();
        return keywords.every(k => rowStr.includes(k));
    });

    state.filteredData = filtered;
    state.total = filtered.length;
    state.currentPage = 1;

    renderDataViewTable(tabId);
}

async function exportCurrentData() {
    const tabId = 'data-view-center';
    const state = viewStateStore[tabId];
    const dataToExport = state.filteredData || state.allData;

    if (!state || !dataToExport || dataToExport.length === 0) {
        return alert('当前没有数据可导出');
    }

    try {
        // Excel导出现在在Main Process处理
        // 使用 electronAPI 选择保存文件
        const filePath = await window.electronAPI.file.selectSaveFile({
            title: '导出数据',
            defaultPath: `${getDataTypeName(state.dataType)}_${new Date().toISOString().slice(0, 10)}.xlsx`,
            filters: [{ name: 'Excel 文件', extensions: ['xlsx'] }]
        });

        if (!filePath) return;

        // 使用 electronAPI 导出数据
        const { keys, fieldDict } = state;
        const headers = keys.map(key => fieldDict[key] || key);

        // 准备导出数据,添加中文表头
        const exportData = dataToExport.map(row => {
            const newRow = {};
            keys.forEach(key => {
                const displayName = fieldDict[key] || key;
                newRow[displayName] = row[key];
            });
            return newRow;
        });

        const result = await window.electronAPI.data.export({
            data: exportData,
            filePath: filePath,
            dataType: getDataTypeName(state.dataType)
        });

        if (result.success) {
            alert(`导出成功！\n文件已保存到：${filePath}`);
        } else {
            alert('导出失败: ' + result.message);
        }

    } catch (error) {
        console.error('导出失败:', error);
        alert('导出失败: ' + error.message);
    }
}

function changeDataViewPageSize(tabId, size) {
    const state = viewStateStore[tabId];
    if (!state) return;

    state.pageSize = parseInt(size);
    state.currentPage = 1;
    renderDataViewTable(tabId);
}

function toggleSelectAll(checkbox) {
    const checkboxes = document.querySelectorAll('.row-checkbox');
    checkboxes.forEach(cb => cb.checked = checkbox.checked);
}

async function handleDeleteData() {
    const checkboxes = document.querySelectorAll('.row-checkbox:checked');
    if (checkboxes.length === 0) return alert('请先选择要删除的数据');

    if (!confirm(`确定要删除选中的 ${checkboxes.length} 条数据吗？此操作不可恢复。`)) return;

    const ids = Array.from(checkboxes).map(cb => parseInt(cb.value));
    const tabId = 'data-view-center';
    const state = viewStateStore[tabId];
    if (!state) return;

    try {
        const caseId = sessionStorage.getItem('currentCaseId');
        // 使用 electronAPI 删除数据
        const result = await window.electronAPI.data.delete({
            caseId,
            dataType: state.dataType,
            ids
        });

        if (result.success) {
            alert('删除成功');
            loadDataToView(state.dataType);
        } else {
            alert('删除失败: ' + result.message);
        }
    } catch (e) {
        alert('操作出错: ' + e.message);
    }
}

async function handleClearData() {
    const tabId = 'data-view-center';
    const state = viewStateStore[tabId];
    if (!state) return alert('请先选择数据类型');

    if (!confirm(`确定要清空所有【${getDataTypeName(state.dataType)}】数据吗？此操作不可恢复！`)) return;

    try {
        const caseId = sessionStorage.getItem('currentCaseId');
        // 使用 electronAPI 清空数据
        const result = await window.electronAPI.data.clear({
            caseId,
            dataType: state.dataType
        });

        if (result.success) {
            alert('清空成功');
            loadDataToView(state.dataType);
        } else {
            alert('清空失败: ' + result.message);
        }
    } catch (e) {
        alert('操作出错: ' + e.message);
    }
}

function openTemplateManager() {
    // const TemplateManager = require('./template'); // Removed
    window.TemplateManager.openTemplateManagementTab();
}


// 带选中状态的加载数据函数
// 带选中状态的加载数据函数
function loadDataToViewWithSelection(dataType) {
    currentDataType = dataType;

    // 更新侧边栏样式
    const container = document.querySelector('.data-sidebar');
    if (container) {
        window.SidebarModule.updateSelection(container, dataType, 'light');
    }

    // 调用原有的加载数据函数
    loadDataToView(dataType);
}

window.DataViewModule = { initializeDataViewModule, showDataViewTab };
